using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Pixysoft
{
    public class ByteBuilder
    {
        MemoryStream stream = new MemoryStream();

        public void Append(string value)
        {
            if (string.IsNullOrEmpty(value))
                return;

            Append(StringCoder.StringToByte(value));
        }

        public void Append(byte value)
        {
            if (value < 0)
                return;

            stream.WriteByte(value);
        }

        public void Append(byte[] value)
        {
            if (value == null)
                return;

            foreach (byte b in value)
                stream.WriteByte(b);
        }

        public void AppendLine()
        {
            Append(Pixysoft.StringCoder.StringToByte("\r\n"));
        }

        public void AppendLine(byte value)
        {
            Append(value);

            Append(Pixysoft.StringCoder.StringToByte("\r\n"));
        }

        public void AppendLine(byte[] value)
        {
            Append(value);

            Append(Pixysoft.StringCoder.StringToByte("\r\n"));
        }

        public void AppendLine(string value)
        {
            Append(Pixysoft.StringCoder.StringToByte(value));

            Append(Pixysoft.StringCoder.StringToByte("\r\n"));
        }

        public byte[] ToByte()
        {
            return stream.ToArray();
        }

        public int Length
        {
            get { return int.Parse(stream.Length.ToString()); }
        }

        public override string ToString()
        {
            long pos = stream.Position;

            stream.Position = 0;

            StreamReader reader = new StreamReader(stream);

            string value = reader.ReadToEnd();

            stream.Position = pos;

            return value;
        }

        public void Remove(int startIndex, int length)
        {
            if (startIndex < 0 || startIndex > Length)
                return;

            if (length < 0)
                return;

            MemoryStream _stream = new MemoryStream();

            byte[] bytes = ToByte();

            int counter = -1;

            foreach (byte bt in bytes)
            {
                counter++;

                if (counter >= startIndex && counter < startIndex + length)
                    continue;

                _stream.WriteByte(bt);
            }

            this.stream.Close();

            this.stream.Dispose();

            this.stream = _stream;
        }


        private void test()
        {
            string value = "hello,fuck you!";
            AppendLine(Pixysoft.StringCoder.StringToByte(value));
            //Remove(2, 1);
            //Console.Write(ToString());
        }
    }
}
